<template>
    <div class="app-container">
        <div>
            <p class="dialogTitle title">当前地震事件:
                <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
                <span v-else>请在地震事件管理中设置当前地震事件</span>
            </p>
        </div>

        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px" v-show="showSearch">
            <el-form-item label="报表类别" prop="reportType">
                <el-select v-model="queryParams.reportType" placeholder="请选择报表类别" clearable>
                    <el-option v-for="item in option" :key="item.dictItemCode" :label="item.dictItemName"
                        :value="item.dictItemCode">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent"
                    @click="importTemplate('20个灾损上报模板.zip')">导出模板</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent" @click="handleAdd">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent" @click="handleSubmit">提交</el-button>
            </el-col>
            <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe row-key="xitId" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" :reserve-selection="true" width="55" />
            <el-table-column label="序号" align="center" width="55">
                <template #default="scope">
                    <span>{{ (queryParams.page - 1) * queryParams.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="报表类别" align="center" prop="reportType" show-overflow-tooltip>
                <template #default="scope">
                    <span style="color: #107ce1;cursor: pointer;" @click="handleDownload(scope.row)">{{ getReportType(scope.row.reportType)
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column label="审核状态" align="center" prop="checkStatus">
                <!-- 审核状态0,1,2,3未提交，未审核，确认，退回 -->
                <template #default="scope">
                    <span v-if="scope.row.checkStatus == '0'">未提交</span>
                    <span v-if="scope.row.checkStatus == '1'">未审核</span>
                    <span v-if="scope.row.checkStatus == '2'">确认</span>
                    <span v-if="scope.row.checkStatus == '3'">退回</span>
                </template>
            </el-table-column>
            <el-table-column label="审核意见" align="center" prop="checkOpinion" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="text" @click="handleImport">导入</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="addRef" label-width="120px" :model="form" :rules="rules">
                <el-row style="margin: 20px 0;">
                    <el-col>
                        <el-form-item label="报表类别" prop="category">
                            <el-select v-model="form.category" placeholder="请选择报表类别" clearable>
                                <el-option v-for="item in option" :key="item.dictItemCode" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="是否有损失值" prop="isHavaLossValue">
                            <el-select v-model="form.isHavaLossValue" placeholder="请选择是否有损失值" clearable>
                                <el-option v-for="item in [{ label: '是', value: '是' }, { label: '否', value: '否' }]"
                                    :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="文件选择" prop="attachmentId">
                            <fileUpload ref="fileUploadRef" :limit="1" @uploadFile="uploadFileSuccess" @delFile="delFile" v-model="form.attach"
                                :fileType="['xls', 'xlsx']" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="save">保 存</el-button>
                    <el-button @click="cancelClick">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="lossReportOn">
import useEventStore from "@/store/modules/event";
import { getAllList, updateData, saveData, getDetail } from "@/api/lossReportManage/lossReportOn.js"
import { MoreFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getDict } from "@/api/system/dict";
const currentEvent = computed(() => useEventStore().currentEvent);
const { proxy } = getCurrentInstance();

const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const showSearch = ref(true);
const open = ref(false);
const title = ref();
const option = ref([])
const multipleSelection = ref([])
const fileUploadRef = ref()
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        reportType: undefined,
    },
    form: {
    },
    rules: {
        category: [{ required: true, message: "请选择报表类别", trigger: "change" }],
        isHavaLossValue: [{ required: true, message: "请选择是否有损失值", trigger: "change" }],
        attachmentId: [{ required: true, message: "请选择文件", trigger: "change" }],
    }
})
const { queryParams, form, rules } = toRefs(data)

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    multipleSelection.value = selection;
    ids.value = selection.map((item) => item.xsemId);
};

//处理附件格式
// function eachFiles(fileName) {
//     let deepFile = JSON.parse(JSON.stringify(proxy.$refs[fileName].fileList))
//     let Ids = []
//     for (var i = 0; i < deepFile.length; i++) {
//         Ids.push(deepFile[i].attachId)
//     }
//     return Ids.join(",");
// }
let m_attachId = null
let m_file = null
// 上传成功回调
function uploadFileSuccess(attachId, file) {
    form.value.attachmentId = attachId
    // console.log('attachId', attachId)
    // console.log('file', file)
    m_attachId = attachId
    m_file = file
}
function delFile(){
    form.value.attachmentId = null;
    m_attachId = null;
    m_file = null;
}

// 导出模版
function importTemplate(name) {
    proxy.downloadTemplate("/template/download", {
        fileName: name
    }, name);
};


// 提交
function handleSubmit() {
    if (!multipleSelection.value || multipleSelection.value.length <= 0) {
        ElMessage({
            type: 'warning',
            message: '请选中数据!'
        });
        return
    }
    const parms = multipleSelection.value.map((item) => item.id).join(',');
    updateData(parms).then(res => {
        proxy.$modal.msgSuccess("提交成功");
        getList();
    })
}

// 导入
function handleAdd() {
    title.value = '导入';
    open.value = true;
    proxy.resetForm('addRef')
}

function handleImport() {
    title.value = '导入';
    open.value = true;
    proxy.resetForm('addRef')
}


// 查看
function handleDownload(row) {
    getDetail({ id: row.id }).then(res => {
        const attachment = res.data.attachment
        location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(attachment.attachId);
    })
}

// 保存
function save() {
    // form.value.enclosurePhoto = eachFiles('uploadRef1');
    proxy.$refs["addRef"].validate(valid => {
        if (valid) {
            proxy.$modal.loading('正在保存，请稍等...')
            // 在这里进行一系列的校验
            const formData = new FormData();
            formData.append("file", m_file.raw);
            formData.append("attachmentId", m_attachId);
            formData.append("xsemId", currentEvent.value.id);
            formData.append("category", form.value.category);
            formData.append("isHavaLossValue", form.value.isHavaLossValue);
            saveData(formData).then(res => {
                proxy.$modal.msgSuccess("导入成功");
                cancelClick()
                proxy.$modal.closeLoading()
                getList();
            }).catch(error=> {
                proxy.$modal.closeLoading()
            })
        }
    })
}
function cancelClick() {
    open.value = false;
    fileUploadRef.value.fileList = []
    m_attachId = null
    m_file = null
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}


/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 查询数据列表 */
function getList() {
    if (currentEvent.value) {
        loading.value = true;
        getAllList({ ...queryParams.value, xsemId: currentEvent.value.id }).then(response => {
            dataList.value = response.data.rows ? response.data.rows : [];
            total.value = response.data.total;
            loading.value = false;
        });
    } else {
        dataList.value = [];
        total.value = 0;
    }
}
function getReportType(val){
  var name = ''
  option.value.forEach(item => {
		if(item.dictItemCode == val) {
			name = item.dictItemName
			return
		}
	})
	return name
}
/** 获取字典值 */
async function getDictData() {
    await getDict("bblb").then(response => {
        option.value = response.data;
    });
}
onMounted(() => {
    setTimeout(() => {
        getList();
    }, 200)
})
getDictData();
</script>
  
<style scoped lang="scss">
.title {
    margin: 0 0 20px !important;
}
</style>
  
  